package com.chw.shop.service.impl;

import com.chw.shop.dao.AreaDao;
import com.chw.shop.entity.po.Area;
import com.chw.shop.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AreaSericeImpl implements AreaService {
    @Autowired
    private AreaDao areaDao;


    private StringBuffer sb=null;
    @Override
    public String queryArea() {
        List<Area> areas = areaDao.selectList(null);
        sb=new StringBuffer("[");
        int count=0;
        for (int i=0;i<areas.size();i++){
            Area area=areas.get(i);
            if (area.getPid()!=null&&area.getPid()==0){
                count++;
                sb.append("{");
                sb.append("\"label\":\"").append(area.getName()).append("\",\"value\":").append(area.getId());
                getChildren(area.getId(),areas);
                sb.append("},");
            }
        }
        return sb.substring(0,sb.length()-1)+"]";
    }

    private void getChildren(Integer id, List<Area> areas) {
        sb.append(",\"children\":[");
        int count=0;
        for (int i=0;i<areas.size();i++){
            Area area=areas.get(i);
            if (area.getPid()!=null&&area.getPid().equals(id)) {
                count++;

                sb.append("{");
                sb.append("\"label\":\"").append(area.getName()).append("\",\"value\":").append(area.getId());
                getChildren(area.getId(), areas);
                sb.append("},");
            }
        }
        if (count>0){
            sb.replace(sb.length()-1,sb.length(),"]");
        }else {
            sb.replace(sb.length()-13,sb.length(),"");
        }
    }
}
